package com.example.musicdemo.ui.activity

import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.graphics.drawable.AnimationDrawable
import android.os.*
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.SeekBar
import com.example.musicdemo.R
import com.example.musicdemo.adapter.PopAdapter
import com.example.musicdemo.base.BaseActivity
import com.example.musicdemo.model.Music
import com.example.musicdemo.service.IService
import com.example.musicdemo.service.AudioService
import com.example.musicdemo.util.Constant.*
import com.example.musicdemo.util.HttpUtil
import com.example.musicdemo.util.StringUtil
import com.example.musicdemo.widget.PlayListPopWindow
import kotlinx.android.synthetic.main.activity_music_player_bottom.*
import kotlinx.android.synthetic.main.activity_music_player_middle.*
import kotlinx.android.synthetic.main.activity_music_player_top.*
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.io.IOException

class AudioPlayActivity : BaseActivity(), View.OnClickListener, SeekBar.OnSeekBarChangeListener,
    AdapterView.OnItemClickListener, PopAdapter.PlayListListener {
    var iService: IService? = null
    private var mDuration: Int = 0
    private var mMusic: Music? = null
    private var mDrawable: AnimationDrawable? = null
    val MSG_PROGRESS = 0
    val MSG_SET_LRC = 1
    private val conn by lazy { AudioConnection() }
    val mPlayListener: PopAdapter.PlayListListener? = null
    private var mPopWindow: PlayListPopWindow? = null
    private val mHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg?.what) {
                MSG_PROGRESS -> startUpdateProgress()
                MSG_SET_LRC -> {
                    lyricView.setSongName((msg.obj as Music).lrc,LRC_NET)

                }
            }
        }
    }

    override fun initListener() {
        //播放状态切换
        state.setOnClickListener(this)
        ivBack.setOnClickListener { finish() }
        //进度条变化监听
        skProgress.setOnSeekBarChangeListener(this)
        //播放模式点击事件
        mode.setOnClickListener(this)
        //上一曲和下一曲点击事件
        pre.setOnClickListener(this)
        next.setOnClickListener(this)
        //播放列表
        playlist.setOnClickListener(this)
        lyricView.setProgressListener {
            if (lyricView.getPlayFlag()) {
                iService?.seekTo(it)
                //更新进度显示
                updateProgress(it)
            }
        }
    }

    override fun initData() {
        //注册eventBus
        EventBus.getDefault().register(this)
        //通过audioService播放音乐
        val intent = intent
        intent.setClass(this, AudioService::class.java)
        //通过intent将list以及position传递过去
        bindService(intent, conn, Context.BIND_AUTO_CREATE)
        //再開啓
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }


    /**
     * 開始更新進度
     */
    private fun startUpdateProgress() {
        //獲取当前进度
        val progress: Int = iService?.getProgress() ?: 0
        //更新进度数据
        updateProgress(progress)
        //定时获取进度
        mHandler.sendEmptyMessage(MSG_PROGRESS)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_audio_player
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.state -> updatePlayState()
            R.id.mode -> updatePlayMode()
            R.id.pre -> iService?.playPre()
            R.id.next -> iService?.playNext()
            R.id.playlist -> showPlayList()
        }

    }

    /**
     * 显示播放列表
     */
    private fun showPlayList() {
        val list = iService?.getPlayList()
        list?.let {
            val adapter = PopAdapter(list, this)
            val bottomH = audio_player_bottom.height
            mPopWindow = PlayListPopWindow(this, adapter, this, window)
            mPopWindow!!.showAsDropDown(audio_player_bottom, 0, -bottomH)

        }
    }

    /**
     * 更新播放模式
     */
    private fun updatePlayMode() {
        iService?.updatePlayMode()
        updatePlayModeBtn()
    }


    /**
     * 根据播放模式修改播放图标
     */
    private fun updatePlayModeBtn() {
        iService?.let {
            when (it.getPlayMode()) {
                AudioService.MODE_ALL -> mode.setImageResource(R.drawable.selector_btn_playmode_order)
                AudioService.MODE_SINGLE -> mode.setImageResource(R.drawable.selector_btn_playmode_single)
                AudioService.MODE_RANDOM -> mode.setImageResource(R.drawable.selector_btn_playmode_random)
            }
        }
    }


    /**
     * 更新播放状态
     */
    private fun updatePlayState() {
        //更新播放状态
        iService?.updatePlayState()
        //更新播放状态的图标
        updatePlayStateBtn()
    }


    /**
     * 根据播放状态更新图标
     */
    private fun updatePlayStateBtn() {
        //获取当前播放状态
        val isPlaying = iService?.isPlaying()
        isPlaying?.let {
            if (isPlaying) {
                //播放了他
                state.setImageResource(R.drawable.selector_btn_audio_play)
                //开始博凡动画
                mDrawable?.start()
                //开始更新进度
                mHandler.sendEmptyMessage(MSG_PROGRESS)
            } else {
                //暂停
                state.setImageResource(R.drawable.selector_btn_audio_pause)
                //停止播放动画
                mDrawable?.stop()
                //停止更新进度条
                mHandler.removeMessages(MSG_PROGRESS)
            }
        }
    }


    /**
     * 进度改变的回调
     */
    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        if (!fromUser) {
            return
        }
        iService?.seekTo(progress)
        //更新界面显示
        updateProgress(progress)

    }


    /**
     * 根据当前进度数据更新界面
     */
    private fun updateProgress(progress: Int) {
        //更新进度数据
        tvProgress.text =
            StringUtil.parseDuration(progress) + "/" + StringUtil.parseDuration(mDuration)
        //更新进度数据
        skProgress.progress = progress
        //更新歌词播放进度
        lyricView.updateProgress(progress)

    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {


    }

    /**
     * 接收eventBus方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(itemBean: Music) {
        //歌词
        if(itemBean.data == null) {
            HttpUtil.sClient.newCall(HttpUtil.getRequest("http://gochiusa.top:3000/lyric?id=${itemBean.id}"))
                .enqueue(object :
                    Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        myToast("获取歌词失败")
                        Log.e("audio play activity", "onFailure: ")
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val strResponse = response.body?.string()
                        val jsonObject = JSONObject(strResponse)
                        val jsonObjectLrc = jsonObject.getJSONObject("lrc")
                        val lyric = jsonObjectLrc.getString("lyric")
                        println("我想看看打印出来的$lyric")
                        itemBean.lrc = lyric
                        val message = mHandler.obtainMessage()
                        message.what = MSG_SET_LRC
                        message.obj = itemBean

                        mHandler.sendMessage(message)
                    }
                })

        }
        lyricView.setSongName(itemBean.name, LRC_LOCAL)
        //记录播放歌曲bean
        this.mMusic = itemBean
        //歌曲名字
        audio_title.text = itemBean.name
        //歌手名
        artist.text = itemBean.ar?.get(0)?.name
        //更新播放状态按钮
        updatePlayStateBtn()
        //动画播放
        mDrawable = iv_audio_anim.drawable as AnimationDrawable
        mDrawable?.start()
        //获取总进度
        mDuration = iService?.getDuration() ?: 0
        //歌词
        lyricView.setSongDuration(mDuration)
        skProgress.max = mDuration
        //更新播放进度
        startUpdateProgress()
        //更新播放模式图标
        updatePlayModeBtn()
    }

    /**
     * 弹出播放列表条目的点击事件
     */
    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        //播放当前歌曲
        iService?.playPosition(position)

    }

    override fun onDestroy() {
        super.onDestroy()
        //手动解绑服务
        unbindService(conn)
        //反注册eventBus
        EventBus.getDefault().unregister(this)
        mHandler.removeCallbacksAndMessages(null)
    }

    inner class AudioConnection : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            iService = service as IService
        }

        /**
         * 意外断开连接时候
         */
        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }

    override fun onPlay(position: Int) {
        iService?.playPosition(position)
        mPopWindow?.dismiss()
    }

    override fun onDelete(position: Int) {
    }


    override fun isDestroyed(): Boolean {

        return super.isDestroyed()

    }


}